#pragma once

#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include "Log.hpp"
namespace MyThread
{
    using namespace log_ns;
    using func_t = std::function<void *(const std::string &)>;
    class Thread
    {
    private:
    public:
        Thread(const std::string &name, func_t func) : _name(name), _func(func)
        {
            LOG(INFO, "%s is success creat!\n", name.c_str());
        }
        void Excute()
        {
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }
        static void *ThreaRoutine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            self->Excute();
            return nullptr;
        }
        void stop()
        {
            if (_isrunning)
            {
                _isrunning = false;
                pthread_cancel(_tid);
            }
        }
        void join()
        {

            if (!_isrunning)
            {
                pthread_join(_tid, nullptr);
                LOG(INFO, "%s jion done\n", _name.c_str());
            }
        }
        bool start()
        {
            if (0 == pthread_create(&_tid, nullptr, ThreaRoutine, this))
            {
                LOG(INFO, "%s is start \n", _name.c_str());
                return true;
            }
            LOG(ERROR, "%s start lose! \n", _name.c_str());
            return false;
        }

        std::string Name()
        {
            return _name;
        }
        ~Thread()
        {
            // stop();
            join();
        }

    private:
        const std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func;
    };

}